package com.raymond.sgip.codec.decoding;

import com.raymond.client.constants.GlobalConstants;
import com.raymond.client.msg.BaseAgreement;
import com.raymond.client.netty.AgreementDecoder;
import com.raymond.sgip.msg.BaseSgipAgreement;
import io.netty.buffer.ByteBuf;

/**
 * @author :  raymond
 * @version :  V1.0
 * @date :  2022-11-10 21:47
 */
public class SgipAgreementDecoder extends AgreementDecoder {

    @Override
    protected BaseAgreement byte2BaseAgreement(ByteBuf bytebuf) {
        return byteBuf2BaseAgreement(bytebuf);
    }

    public static BaseAgreement byteBuf2BaseAgreement(ByteBuf bytebuf) {
        BaseSgipAgreement baseAgreement = new BaseSgipAgreement();
        baseAgreement.setTotalLength(bytebuf.readInt());
        baseAgreement.setCommandId(bytebuf.readInt());
        baseAgreement.setGateId(bytebuf.readInt());
        baseAgreement.setTimeStamp(bytebuf.readInt());
        baseAgreement.setSequenceId(bytebuf.readInt());
        baseAgreement.setHeadLength(20);
        baseAgreement.setBodyLength(baseAgreement.getTotalLength() - baseAgreement.getHeadLength());
        if (baseAgreement.getBodyLength() > 0) {
            baseAgreement.setBodyBuffer(new byte[baseAgreement.getBodyLength()]);
            assert(baseAgreement.getBodyLength() == bytebuf.readableBytes());
            bytebuf.readBytes(baseAgreement.getBodyBuffer());
        } else {
            baseAgreement.setBodyBuffer(GlobalConstants.EMPTY_BYTES);
        }
        return baseAgreement;
    }
}
